$(function () {
    layui.use(['table', 'dropdown', 'form'], function () {
        table = layui.table,
            form = layui.form,
            $ = layui.$;

        // 创建渲染实例
        table.render({
            elem: '#exampleTable'
            , id: 'exampleTable'
            , method: "get"
            , contentType: 'multipart/form-data'
            , url: "/jzweb/jazCourses/selCourseList"
            , cellMinWidth: 80
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                , curr: pages //设定初始在第 5 页
                , groups: 5 //只显示 1 个连续页码
                , limit: 15
                , limits : [15,30,50,100,200]
            }
            , request: {
                pageName: 'current',
                limitName: 'size'
            }
            , where: {
                name: $("#username").val(),
                teacherName: $("#teacherName").val(),
            }
            , defaultToolbar: false
            , loading: false
            , cols: [[ {
                field: "",
                title:'',
                align: 'center',
                maxWidth: 30,
                minHeight:30,
                templet:function (d) {
                    let myd =d;
                    myd.introduce='';
                    myd=JSON.stringify(myd).replaceAll("\"", "|")
                    return `<i class="layui-icon myIcons layui-icon-triangle-r"  onclick='openS("${myd}",this)'></i>`
                }
            },
                {
                    field: 'name',
                    title: '课程名称',
                    align: 'center',
                    templet: function (d) {
                        return   `<span>${d.name}</span>`

                    }
                },
                {
                    field: 'teacherNames',
                    title: '课程讲师',
                    align: 'center',
                    templet: (d) => {
                        return `<span>${d.teacherNames == '' ? '' :d.teacherNames.replace(/\[|\]/g,'')}</span>`
                    }
                },
                {
                    field: 'state',
                    title: '课程状态',
                    align: 'center',
                    templet: (d) => {
                        return`<span>${ d.state == '0' ? '上架' : d.state == '1' ? '下架' : '已删除'}</span>`
                    }
                },
                {
                    field: 'sort',
                    title: '优先级',
                    width:40,
                    align: 'center',
                    templet: function (d) {
                        return  `<span>${d.sort}</span>`

                    }
                },
                {
                    field: 'checkbox',
                    title: '是否上架',
                    align: 'center',
                    width: 40,
                    templet: (d) => {
                        return upAndDownPrices?( (d.state == '0' ? ` 
      <input type="checkbox" checked ` : '<input type="checkbox" ') + ` name="open"  value="${d.id}"
      title="上架|下架" myid="${d.id}" lay-skin="switch" lay-filter="switchTest" title="是否启用"> 
						`):(d.state=='0'?'<span class="label label-primary">上架</span>':'<span class="label label-warning">下架</span>')
                    }
                },
                {
                    field: 'createrDate',
                    title: '创建时间',
                    align: 'center',
                    templet: function (d) {
                        return  `<span>${d.createrDate}</span>`

                    }
                },
                {
                    title: '操作',
                    field: 'id',
                    align: 'center',
                    templet: function (d) {
                        var a = '<a  class="btn btn-primary btn-sm '+look_add_Z+ ' " href="#" mce_href="#" title="新增章节" onclick="addInfo(\''
                            + d.id + '\',\'' + 0 + '\',\'' +('exampleTable'+d.id) + '\' )"><i class="layui-icon layui-icon-addition fa" style="font-size: inherit;"></i></a> ';
                        //parentId
                        var bj = '<a  class="btn btn-primary btn-sm ' + look_edit_K+' " href="#" mce_href="#" title="编辑" onclick="edit(\''
                            + d.id + '\')"><i class="fa fa-edit"></i></a> ';

                        var ss = '<a class="btn btn-success btn-sm ' + look_remove_K +'" href="#" title="删除"  mce_href="#" onclick="remove(\''
                            + d.id
                            + '\')"><i class="fa fa-remove"></i></a>';

                        return a + bj + ss;
                    }
                }
            ]]
            , response: {
                statusCode: 0 //重新规定成功的状态码为 200，table 组件默认为 0
            }
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                if (res.code != 0) {

                    return false;
                }

                if(Number(res.data.total)>0&&res.data.records.length==0){
                    pages--;
                    if(pages>0) {
                        table.reload('exampleTable', {
                            page: {curr: pages},
                            where: {name: $("#username").val(), teacherName: $("#teacherName").val()}
                        })
                    }
                }


                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            }
            , jump: function (obj, first) {
                //首次不执行
                if (!first) {
                    pages = obj.curr
                }
            }
            , error: function (res, msg) {

            }

            , done: function (res) {
                form.render()
                hindLoading()
            }
        });
        form.on('switch(switchTest)', function (data) {
            let id = $(data.othis[0].parentNode).find('input').attr('myid')
            var loadIndex = layer.load(0);
            AjaxGet('/jzweb/jazCourses/editStatus', {id}).then(function (response) {
                parent.layer.msg("操作成功");
                layer.close(loadIndex)
                load();
            }).catch(error => {
                layer.msg(error.msg)
                layer.close(loadIndex)
                load();
            })


        })
        var $ = layui.$, active = {
            reload: function () {
                //执行重载
                table.reload('exampleTable', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: {
                        name: $("#username").val(),
                        teacherName: $("#teacherName").val(),
                    }
                });
            }
        };

        $('.demoTable .layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });


    });

});
var table=null;
const openS = (item, e) => {
    let mytr = $(e).parent().parent().parent()
    let d = JSON.parse(item.replaceAll("|", "\""))
    if ($(e).hasClass("layui-icon-triangle-r")) {
        //当前的tr,加入table
        const mytableId='exampleTable'+d.id
        const myWidth=mytr[0].clientWidth-508
        console.log('宽度获取', myWidth )
        $(mytr).after(`
		<tr class="myTr" data-index="${mytr.attr('data-index')+'-'+0}">
		  <td  colspan="8"  class="myTr_Td"> 
	        <table class="layui-hide" id="${mytableId}" lay-filter="${mytableId}"></table>
	      </td>
		</tr>
		`)
        // 创建渲染实例
        table.render({
            elem: `#${mytableId}`
            , id: `${mytableId}`
            , method: "get"
            , contentType: 'multipart/form-data'
            , url: "/jzweb/jazCoursesChapter/selectCourseChapter"
            , cellMinWidth: 80
            ,page: false
            , where: {
                courseId: d.id,
            }
            , defaultToolbar: false
            , loading: false
            , cols: [[ {
                field: "",
                title:'',
                align: 'center',
                maxWidth: 30,
                width: 30,
                minHeight:30,
                templet:function (d) {
                    let myd = JSON.stringify(d).replaceAll("\"", "|")
                    return `<i class="layui-icon myIcons layui-icon-triangle-r"  onclick='openSTwo("${myd}",this,"${d.mytableId}")'></i>`
                }
               },
                {
                    field: 'chapterName',
                    title: '章节名称',
                    align: 'center',
                    width:200,
                    templet: function (d) {
                        return  `<span>${d.chapterName}</span>`

                    }
                },
                {
                    field: 'videoUrl',
                    title: '视频链接',
                    align: 'center',
                    width:myWidth,
                    templet: function (d) {
                        /**
                         *
                         *                         <video width="100" height="20" controls>
                         *                             <source  src="${d.videoUrl}" type="${d.videoUrl.indexOf("mp4")>0?'video/mp4':
                         *                             d.videoUrl.indexOf("ogg")>0?'video/ogg':
                         *                                 d.videoUrl.indexOf("webm")>0?'video/webm':
                         *                                     d.videoUrl.indexOf("webm")>0?'video/webm':''
                         *                         }">
                         *                      </video>
                         */
                        // return  `<span></span>`
                        return  `
                        <div class="MyVideos"> 
                        <div class="title">${d.videoUrl}</div>
                        </div> 
                        `

                    }
                },
                {
                    field: 'sort',
                    title: '优先级',
                    width:40,
                    align: 'center',
                    templet: function (d) {
                        return  `<span>${d.sort}</span>`

                    }
                },
                {
                    title: '操作',
                    field: 'id',
                    align: 'center',
                    width:140,
                    templet: (d)=> {
                        var a = '<a  class="btn btn-primary btn-sm ' + look_add_X+ ' " href="#" mce_href="#" title="新增小节" onclick="addInfo(\''
                            + d.id + '\',\'' + 1 + '\',\'' +('exampleTable'+d.parentId) + '\' )"><i class="layui-icon layui-icon-addition fa" style="font-size: inherit;"></i></a> ';

                        var bj = '<a  class="btn btn-primary btn-sm ' + look_edit_Z+ ' " href="#" mce_href="#" title="编辑" onclick="editInfo(\''
                            + d.id + '\',\'' + 0 + '\',\'' +('exampleTable'+d.parentId) + '\')"><i class="fa fa-edit"></i></a> ';

                        var ss = '<a class="btn btn-success btn-sm ' +look_remove_Z +'" href="#" title="删除"  mce_href="#" onclick="removeInfo(\''
                            + d.id + '\',\'' + 0 +  '\',\'' + d.mytableId + '\'  )"><i class="fa fa-remove"></i></a>';

                        return a + bj + ss;
                    }
                }
            ]]
            , response: {
                statusCode: 0 //重新规定成功的状态码为 200，table 组件默认为 0
            }
            , parseData:  (res)=> { //将原始数据解析成 table 组件所规定的数据
                if (res.code != 0) {
                    return false;
                }
                console.log('mytableId',mytableId)
                const mydata=[]
                res.data.forEach(item=>{item.mytableId=mytableId;mydata.push(item)})
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "data": mydata
                };
            }
            , error: function (res, msg) {

            }

            , done: function (res) {
                form.render()
                hindLoading()
            }
        });
        $(e).removeClass('layui-icon-triangle-r')
        $(e).addClass('layui-icon-triangle-d')
    } else {
        $(e).removeClass('layui-icon-triangle-d')
        $(e).addClass('layui-icon-triangle-r')
        $(mytr).next().remove()
    }
}
const openSTwo=(item, e,openmytableId) =>{
    console.log('openSTwo',openmytableId)
    let mytr = $(e).parent().parent().parent()
    let d = JSON.parse(item.replaceAll("|", "\""))
    if ($(e).hasClass("layui-icon-triangle-r")) {
        //当前的tr,加入table
        let myTRs = ``
        /**
         *
         *                             <video width="100" height="20" controls>
         *                                 <source  src="${item.videoUrl}" type="${item.videoUrl.indexOf("mp4")>0?'video/mp4':
         *                                  item.videoUrl.indexOf("ogg")>0?'video/ogg':
         *                                  item.videoUrl.indexOf("webm")>0?'video/webm':
         *                                  item.videoUrl.indexOf("webm")>0?'video/webm':''
         *                                 }">
         *                             </video>
         */
        console.log('mytr')
        d.childChapterVos.forEach((item,index) => {
            myTRs += `<tr myItemId="${d.id}" data-index="${mytr.attr('data-index')+'-'+index}">
                        <td align="center" class="layui-table-cell"> </td>
                        <td align="center" ><div class="layui-table-cell" align="center"><span>${item.chapterName}</span</div></td>
                        <td align="center" ><div class="layui-table-cell" align="center"> 
                        <div class="MyVideos"> 
                            <div class="title"> ${item.videoUrl}</div>
                            </div> 
                        </div>
                        </td>
                        <td align="center" ><div class="layui-table-cell" align="center"><span>${item.sort}</span></div></td> 
                        <td align="center" class="layui-table-cell">
                          <a class="btn btn-primary btn-sm ${look_edit_X}" href="#" mce_href="#" title="编辑" onclick="editInfo('${item.id}','1','exampleTable${d.parentId}')"><i class="fa fa-edit"></i></a> 
                          <a class="btn btn-success btn-sm ${look_remove_X}" href="#" title="删除"  mce_href="#" onclick="removeInfo('${item.id}','1','${openmytableId}')"><i class="fa fa-remove"></i></a>
                        </td>
            
                     </tr>`
        })
        $(mytr).after(`${myTRs}
		`)
        $(e).removeClass('layui-icon-triangle-r')
        $(e).addClass('layui-icon-triangle-d')
    } else {
        $(e).removeClass('layui-icon-triangle-d')
        $(e).addClass('layui-icon-triangle-r')
        $(mytr).parent().find(`tr[myItemId='${d.id}']`).remove()
    }
}
var pages = 1;

/**
 * 所有的重置表格
 */
function load(){
    layui.use(['table'], ()=>{
        layui.table.reload('exampleTable',{
            where: {
                name: $("#username").val(),
                teacherName: $("#teacherName").val(),
            }
        })
    })
}

$("#add").click(function () {

    let toIndex = layer.open({
        type: 2,
        title: '新增课程',
        maxmin: true,
        shadeClose: false,
        area: ['800px', '500px'],
        content: '/jzweb/jazCourses/add/add/0'
    });
    layer.full(toIndex);
})

function edit(id) {
    let toIndex = layer.open({
        type: 2,
        title: '课程编辑',
        maxmin: true,
        shadeClose: false,
        area: ['800px', '500px'],
        content: `/jzweb/jazCourses/add/edit/${id}`
    });
    layer.full(toIndex);
}
function tableReload(tableName){
    console.log('tableName',tableName)
    //执行重载
    table.reload(tableName);
}
function addInfo(id,index,tableName) {
    let title='',type=''
    switch (index){
        case "0":
            title='新增章节'
            type="addZ"
            break;
        case "1":
            title='新增小节'
            type="addJ"
            break;
    }
    let toIndex = layer.open({
        type: 2,
        title: title,
        maxmin: true,
        shadeClose: false,
        area: ['900px', '500px'],
        content: `/jzweb/jazCourses/addInfo/${type}/${id}/${tableName}`
    });
    // layer.full(toIndex);
}

function editInfo(id,index,tableName) {
    let title='',type=''
    switch (index){
        case "0":
            title='编辑章节'
            type="editZ"
            break;
        case "1":
            title='编辑小节'
            type="editJ"
            break;
    }
    let toIndex = layer.open({
        type: 2,
        title: title,
        maxmin: true,
        shadeClose: false,
        area: ['800px', '500px'],
        content: `/jzweb/jazCourses/addInfo/${type}/${id}/${tableName}`
    });
    // layer.full(toIndex);
}

function remove(id) {

    layer.confirm('确定要删除选中的记录？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: '/jzweb/jazCourses/remove',
            type: "post",
            data: {
                'id': id
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.msg(r.msg);
                    load();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}
function removeInfo(id,index,mytableId) {
    console.log('openSTwo',mytableId)

    let title='',type=''
    switch (index){
        case "0":
            title='删除章节'
            break;
        case "1":
            title='删除小节'
            break;
    }
    layer.confirm(`确定要删除选中的${title}？`, {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: '/jzweb/jazCoursesChapter/remove',
            type: "post",
            data: {
                'id': id
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.msg(r.msg);
                    //刷新当前表
                    table.reload(mytableId);
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}